﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Me.Prettyprint.Cassandra.Utils;

namespace Me.Prettyprint.Hector.Api.Beans
{
    public class Component<T>
    {
        protected T tvalue;

        public Component(T value, ByteBuffer buff, Serializer<T> serializer, string comparator, ComponentEquality equality)
        {
            Serializer = serializer;
            tvalue = value;
            Bytebuffer = buff;
            Comparator = comparator;
            Equality = equality;
        }
        public Serializer<T> Serializer
        {
            get;
            set;
        }
        public T Value
        {
            get
            {
                return GetValue(Serializer);
            }
        }
        public ByteBuffer Bytebuffer
        {
            get;
            private set;
        }
        public ComponentEquality Equality
        {
            get;
            set;
        }
        public string Comparator
        {
            get;
            set;
        }
        public T GetValue(Serializer<T> s)
        {
            // if the method was called directly the serializer could be null
            // in the case, we use the default serializer
            if (s == null)
            {
                s = (Serializer<T>)Serializer;
            }
            if ((tvalue == null) && (Bytebuffer != null) && (s != null) || tvalue.Equals(default(T)))
            {
                return s.FromByteBuffer(Bytebuffer);
            }
            return tvalue;
        }
        public ByteBuffer GetValueByteBuffer(Serializer<T> s)
        {
            if (Bytebuffer == null)
            {
                if (tvalue != null && s != null)
                {
                    return s.ToByteBuffer(tvalue);
                }
                else
                {
                    return new ByteBuffer(new byte[0]);
                }
            }
            else
            {
                return Bytebuffer.Duplicate();
            }
        }
        public override string ToString()
        {
            return "Component [" + Value + "]";
        }
    }
}
